package com.campus.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.campus.job.StaticData;
import com.campus.campus.job.entity.CampusCards;
import com.campus.campus.job.entity.UtilityConsumptionRecord;
import com.campus.campus.mapper.CampusCardsMapper;
import com.campus.campus.mapper.StaticDataMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.campus.mapper.UtilityConsumptionRecordMapper;
import com.campus.campus.service.ICampusCardsService;
import com.campus.campus.service.IStaticDataService;
import com.campus.campus.service.IUtilityConsumptionRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 水费或电费消耗记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-07
 */
@Service
public class StaticDataServiceImpl extends ServiceImpl<StaticDataMapper, StaticData> implements IStaticDataService {


    @Autowired
    private IUtilityConsumptionRecordService utilityConsumptionRecordService;

    @Autowired
    private CampusCardsMapper campusCardsMapper;

    @Autowired
    private StaticDataMapper staticDataMapper;

    @Autowired
    private UtilityConsumptionRecordMapper utilityConsumptionRecordMapper;

    @Override
    public void insertData() {

        List<Integer> cardIds = campusCardsMapper.selectList(null).stream().map(CampusCards::getId).toList();

        LambdaQueryWrapper<UtilityConsumptionRecord> queryWrapper = new LambdaQueryWrapper<>();

        // 获取昨天晚上24:00（即昨天的00:00）和今天晚上24:00（即明天的00:00）
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfYesterday = now.minusDays(0).toLocalDate().atStartOfDay(); // 昨天00:00
        LocalDateTime endOfToday = now.toLocalDate().plusDays(1).atStartOfDay(); // 今天24:00（即明天00:00）
        // 如果需要格式化日期并作为字符串比较（可选）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startOfYesterdayFormatted = startOfYesterday.format(formatter);
        String endOfTodayFormatted = endOfToday.format(formatter);

        insertElectricity(cardIds, queryWrapper, startOfYesterdayFormatted, endOfTodayFormatted);

        insertWater(cardIds, queryWrapper, startOfYesterdayFormatted, endOfTodayFormatted);


    }

    private void insertElectricity(List<Integer> cardIds, LambdaQueryWrapper<UtilityConsumptionRecord> queryWrapper, String startOfYesterday, String endOfToday) {
        cardIds.forEach(cardId -> {
            List<UtilityConsumptionRecord> records = utilityConsumptionRecordMapper.getList(startOfYesterday,endOfToday,cardId);
            if (records.size() > 0) {
                // 统计电费
                BigDecimal totalElectricity = records.stream()
                        .map(UtilityConsumptionRecord::getDeductionAmount) // 使用 map 转换为 BigDecimal 流
                        .reduce(BigDecimal.ZERO, BigDecimal::add); // 使用 reduce 累加

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime startOfYesterday1 = now.minusDays(1).toLocalDate().atStartOfDay(); // 昨天00:00
                String time = startOfYesterday1.format(formatter);
                StaticData staticData=new StaticData();
                staticData.setConsumptionFee(totalElectricity);
                staticData.setFeeType("电费");
                staticData.setCampusCardId(cardId);
                staticData.setTimes(time);
                int insert = staticDataMapper.insert(staticData);
                if(insert<0){
                    System.out.println("插入失败");
                }
            }

        });
    }

    private void insertWater(List<Integer> cardIds, LambdaQueryWrapper<UtilityConsumptionRecord> queryWrapper, String startOfYesterday, String endOfToday) {
        cardIds.forEach(cardId -> {
//            queryWrapper.eq(UtilityConsumptionRecord::getType, "水费")
//                    .eq(UtilityConsumptionRecord::getCampusCardId, cardId)
//                    .ge(UtilityConsumptionRecord::getUpdateTime, startOfYesterday) // 从昨天00:00开始
//                    .lt(UtilityConsumptionRecord::getUpdateTime, endOfToday); // 到今天24:00（明天00:00之前）

            List<UtilityConsumptionRecord> records = utilityConsumptionRecordMapper.getListWater(startOfYesterday,endOfToday,cardId);
            if (records.size() > 0) {
                // 统计电费
                BigDecimal totalElectricity = records.stream()
                        .map(UtilityConsumptionRecord::getDeductionAmount) // 使用 map 转换为 BigDecimal 流
                        .reduce(BigDecimal.ZERO, BigDecimal::add); // 使用 reduce 累加

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime startOfYesterday1 = now.minusDays(1).toLocalDate().atStartOfDay(); // 昨天00:00
                String time = startOfYesterday1.format(formatter);
                StaticData staticData=new StaticData();
                staticData.setConsumptionFee(totalElectricity);
                staticData.setFeeType("水费");
                staticData.setCampusCardId(cardId);
                staticData.setTimes(time);
                int insert = staticDataMapper.insert(staticData);
                if(insert<0){
                    System.out.println("插入失败");
                }
            }

        });
    }

}
